<template>
  <div style="padding: 20px">
    <div>广度遍历id：{{ arr }}</div>
    <div>深度遍历id：{{ objs.map((e) => e.id) }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      root: {
        id: 1,
        children: [
          {
            id: 11,
            children: [
              { id: 111, children: [{ id: 1111, children: [] }] },
              { id: 112, children: [{ id: 1121, children: [] }] },
            ],
          },
          {
            id: 12,
            children: [{ id: 121, children: [{ id: 1211, children: [] }] }],
          },
          {
            id: 13,
            children: [
              { id: 131, children: [{ id: 1311, children: [] }] },
              {
                id: 132,
                children: [
                  { id: 1321, children: [] },
                  { id: 1322, children: [] },
                ],
              },
            ],
          },
        ],
      },
      arr: [],
      objs: [],
    };
  },
  methods: {
    // 广度优先遍历 循环版本
    bfs(obj) {
      const objs = [];
      if (obj.children.length) {
        const arr = [];
        arr.unshift(obj);
        while (arr.length) {
          const item = arr.shift();
          objs.push(item);
          // 把当前对象的子元素进行遍历
          for (let i = 0; i < item.children.length; i++) {
            arr.push(item.children[i]);
          }
        }
      }
      return objs;
    },
    // 深度优先遍历 循环版本
    dfs(obj) {
      const objs = [];
      if (obj.children.length) {
        const arr = [];
        arr.push(obj);
        while (arr.length) {
          const item = arr.pop();
          objs.push(item);
          // 把当前对象的子元素进行遍历
          for (let i = item.children.length - 1; i >= 0; i--) {
            arr.push(item.children[i]);
          }
        }
      }
      return objs;
    },
    // 深度优先遍历递归
    dfs1(obj, objs) {
      objs.push(obj);
      for (let i = 0; i < obj.children.length; i++) {
        this.dfs1(obj.children[i], objs);
      }
    },
    // 广度优先遍历递归
    bfs1(obj, objs, arr) {
      if (obj) objs.push(obj);
      if (!arr.length) return;
      // 取出第一项 遍历进objs
      const item = arr.shift();
      item.children.forEach((e) => {
        arr.push(e);
      });
      this.bfs1(item, objs, arr);
    },
  },
  mounted() {
    // this.arr = this.bfs(this.root).map((e) => e.id);
    // this.dfs1(this.root,this.objs);
    this.bfs1(null, this.arr, [this.root]);
    this.arr = this.arr.map((e) => e.id);
    this.objs = this.dfs(this.root);
  },
};
</script>
<style scoped lang="less"></style>
